﻿using System;
using umbraco.BusinessLogic;
using umbraco.presentation.masterpages;
using TheOutfield.UmbExt.PageNotifications.Util;
using System.Web.UI.WebControls;

namespace TheOutfield.UmbExt.PageNotifications
{
    public class SaveConfirmation : ApplicationBase
    {
        public SaveConfirmation()
        {
            umbracoPage.Load += UmbracoPageLoad;
        }

        protected void UmbracoPageLoad(object sender, EventArgs e)
        {
            var rootControl = sender as umbracoPage;
            if (rootControl == null)
                return;

            var path = rootControl.Page.Request.Path.ToLower();
            if (!path.Contains("/umbraco/") && !path.Contains("edit"))
                return;
            
            var environment = Environment.Instance.ConfiguredEnvironment;

            foreach (var notification in Config.Instance.Notifications)
            {
                var notif = notification;

                if (notif.Type == NotificationType.SaveWarning && notif.SaveWarning.Environments.Contains(environment) == false)
                    return;
            }

            var userTypeAlias = new User(umbraco.helper.GetCurrentUmbracoUser().Id).UserType.Alias;
            foreach (var notification in Config.Instance.Notifications)
            {
                var notif = notification;

                if (notif.Type == NotificationType.Environment && notif.IndicatorBar.UserTypeAliases.Contains(userTypeAlias) == false)
                    return;
            }

            var placeHolder = (ContentPlaceHolder)ControlUtil.FindControlRecursive(rootControl, "body");
            if (placeHolder == null)
                return;

            AddSaveConfirmation(placeHolder);
        }

        protected void AddSaveConfirmation(ContentPlaceHolder placeHolder)
        {
            var literal = new Literal { Text = "<script type=\"text/javascript\" src=\"/umbraco/plugins/pageNotifications/pageNotifications.js\"></script>" };

            var panel = new Panel();
            panel.Controls.Add(literal);

            placeHolder.Controls.Add(panel);
        }
    }
}